package com.example.login.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类
 */
@Component
public class HttpClientUtil {
    // 创建可配置的HttpClient实例
    private static final CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(5000)    // 连接超时时间
                    .setSocketTimeout(10000)    // 读取超时时间
                    .build())
            .build();

    /**
     * 发送POST请求（支持表单格式）
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  表单参数
     * @return 响应结果字符串
     */
    public static String postForm(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        configRequest(httpPost, headers);

        // 构造表单参数
        List<NameValuePair> paramPairs = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(paramPairs, StandardCharsets.UTF_8));

        return executeRequest(httpPost);
    }

    // 配置通用请求头
    private static void configRequest(HttpPost httpPost, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    // 执行请求并处理响应
    private static String executeRequest(HttpPost httpPost) throws IOException {
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity responseEntity = response.getEntity();
            StringBuilder result = new StringBuilder();

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            }
            return result.toString();
        }
    }
}